package cn.hinglo.common.interceptors.kit;

import cn.hinglo.common.entity.Result;
import cn.hinglo.common.interceptors.base.BaseInterceptor;
import cn.hinglo.common.util.ResultKit;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;

/**
 * @createTime: 2020/08/05 : 11:46
 * @author: HingLo
 * @description: 返回值拦截器，用于直接封装返回数据类型
 */
public class ReturnInterceptor extends BaseInterceptor {
    @Override
    public Class<? extends Annotation> ignoreAnnotation() {
        return null;
    }

    @Override
    public void preHandle(HttpServletRequest request, HttpServletResponse response, Invocation inv) {
        inv.invoke();
        // 返回值非 void 类型返回
        Controller controller = inv.getController();
        String returnType = inv.getMethod().getReturnType().getName();
        if (!"void".equals(returnType)) {
            Object result = inv.getReturnValue();
            if (result != null) {
                if (result instanceof Result) {
                    controller.renderJson(result);
                } else {
                    controller.renderJson(ResultKit.success(result));
                }
            } else {
                controller.renderJson(ResultKit.success());
            }
        } else {
            if (controller.getRender() == null) {
                controller.renderJson(ResultKit.error("你的方法没有返回值类型,并且未指定返回render方法"));
            }
        }
    }

}
